package com.abc.limit.demo;

import com.google.common.util.concurrent.RateLimiter;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class LimitMain {

   public static void main(String[] args) throws Exception{

      //10代表一秒最多多少个
      RateLimiter limiter = RateLimiter.create(10);

      Thread.sleep(1000);

      System.out.println("开始时间=" + System.currentTimeMillis());

      for (int i = 0; i < 100; i++) {
         new UserRequest(limiter).start();
      }


      System.out.println("结束时间=" + System.currentTimeMillis());

   }

   private static class UserRequest extends Thread {
      private RateLimiter limiter;

      public UserRequest(RateLimiter limiter) {
         this.limiter = limiter;
      }

      @Override
      public void run() {
         double limit = limiter.acquire();
         boolean tryAcquire = limiter.tryAcquire();
         if (tryAcquire){
            //获取到
            System.out.println(Thread.currentThread().getName() + "获取到了令牌，执行任务 "+tryAcquire);
         }else {
            System.out.println(Thread.currentThread().getName() + "获取到了令牌，执行任务 "+tryAcquire);
         }

      }
   }

}
